// src/hooks/useLoginForm.ts
import { useState } from 'react';
import type { LoginFormData, LoginResponseData } from '@/types/types';
import { loginUser } from '@/services/authService';
import { useNavigate } from 'react-router-dom';
import { useUserStore } from '@/store/userStore';
import { canViewScholarsDashboardContent, canViewSponsorsDashboardContent } from '@/utils/permissionUtils';

export function useLoginForm() {
  const [form, setForm] = useState<LoginFormData>({
    email: '',
    password: '',
  });

  const [emailError, setEmailError] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const [generalError, setGeneralError] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  const navigate = useNavigate();
  const setUser = useUserStore((state) => state.setUser);

  const setEmail = (email: string) => {
    setForm((prev) => ({ ...prev, email }));
    if (emailError) setEmailError('');
    if (generalError) setGeneralError('');
  };

  const setPassword = (password: string) => {
    setForm((prev) => ({ ...prev, password }));
    if (passwordError) setPasswordError('');
    if (generalError) setGeneralError('');
  };

  const validate = () => {
    let valid = true;

    // Email validation
    if (!form.email.trim()) {
      setEmailError('Email is required');
      valid = false;
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) {
      setEmailError('Please enter a valid email address');
      valid = false;
    } else {
      setEmailError('');
    }

    // Password validation
    if (!form.password.trim()) {
      setPasswordError('Password is required');
      valid = false;
    } else if (form.password.length < 8) {
      setPasswordError('Password must be at least 8 characters');
      valid = false;
    } else {
      setPasswordError('');
    }

    return valid;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validate()) return;

    setIsLoading(true);
    setGeneralError('');

    try {
      const response: LoginResponseData = await loginUser(form);
      const { token, user } = response;

      // Store token
      localStorage.setItem('token', token);

      // Map backend response to frontend format
      setUser({
        userId: String(user.userId || ''),
        firstName: user.firstName,
        lastName: user.lastName,
        email: user.email,
        role: user.role,
        permissions: user.permissions,
      });

      setTimeout(() => {
        const canViewScholars = canViewScholarsDashboardContent(user.permissions);
        const canViewSponsors = canViewSponsorsDashboardContent(user.permissions);

        if (canViewSponsors) {
          navigate('/sponsors');
        } else if (canViewScholars) {
          navigate('/scholars');
        } else {
          navigate('/sponsors');
        }
      }, 100);
    } catch (error: unknown) {
      console.error('Login error:', error);

      if (error && typeof error === 'object' && 'response' in error && error.response && typeof error.response === 'object' && 'status' in error.response) {
        if (error.response.status === 401) {
          setGeneralError('Invalid email or password. Please try again.');
        } else if (error.response.status === 429) {
          setGeneralError('Too many login attempts. Please wait a moment and try again.');
        } else {
          setGeneralError('Login failed. Please try again later.');
        }
      } else if (error instanceof Error && error.message === 'Network Error') {
        setGeneralError('Network error. Please check your connection and try again.');
      } else {
        setGeneralError('Login failed. Please try again later.');
      }
    } finally {
      setIsLoading(false);
    }
  };

  return {
    ...form,
    setEmail,
    setPassword,
    handleSubmit,
    emailError,
    passwordError,
    generalError,
    isLoading,
  };
}